package com.eshop.utils;

import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.ArrayList;
import java.util.List;
import java.util.Arrays;

public class RegexUtil
{
    public static String converProductDescription(final String str) {
        final StringBuilder sb = new StringBuilder();
        final List<String> imgArr = Arrays.asList(str.split("p><img"));
        for (int i = 0; i < imgArr.size(); ++i) {
            String img = imgArr.get(i);
            if (i != imgArr.size() - 1) {
                img += "p><img";
            }
            if (img.indexOf("src") > 0) {
                if (img.indexOf("style=") > 0) {
                    final String rgex = "style=\"(.*?)\"";
                    final String rgexStr = getSubUtilSimple(img, rgex);
                    if (rgexStr.indexOf("max-width: 100%;") < 0) {
                        img = img.replace(rgexStr, rgexStr + "max-width: 100%");
                    }
                }
                else {
                    img = " style=\"max-width: 100%;\"" + img;
                }
            }
            sb.append(img);
        }
        return sb.toString();
    }
    
    public static List<String> getSubUtil(final String soap, final String rgex) {
        final List<String> list = new ArrayList<String>();
        final Pattern pattern = Pattern.compile(rgex);
        final Matcher m = pattern.matcher(soap);
        while (m.find()) {
            int i = 1;
            list.add(m.group(i));
            ++i;
        }
        return list;
    }
    
    public static String getSubUtilSimple(final String soap, final String rgex) {
        final Pattern pattern = Pattern.compile(rgex);
        final Matcher m = pattern.matcher(soap);
        if (m.find()) {
            return m.group(1);
        }
        return "";
    }
}
